package com.hsmpay.mobile.util.interceptor;

import com.hsmpay.mobile.pojo.device.DeviceKey;
import com.hsmpay.mobile.service.device.DeviceKeyService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.mobile.action.base.MobileBaseAction;
import com.hsmpay.mobile.action.user.UserAction;
import com.hsmpay.mobile.service.user.UserService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import java.util.Map;

public class CheckLoginInterceptor extends AbstractInterceptor {
    private static final long serialVersionUID = 3335966265187255000L;
    static Logger log = Logger.getLogger(CheckLoginInterceptor.class);
    @Resource(name = "userService")
    protected UserService<User, Long> userService;
    @Resource(name = "deviceKeyService")
    protected DeviceKeyService<DeviceKey, Long> deviceKeyService;//设备信息

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        MobileBaseAction action = (MobileBaseAction) invocation.getAction();
        ActionContext act = invocation.getInvocationContext();
        //Map<String,Object> sesstionMap = act.getSession();//获得session
        //Map<String, Object> params = act.getParameters();//获得request中的参数
        Map<String, Object> sessionMap = null;
        User user = null;
        JSONObject js = null;
        try {
            log.debug("访问URI：###" + action.getRequest().getRequestURL() + "###");

            //指定刷卡器只能在指定客户端上使用
            String fc_data = ((MobileBaseAction) invocation.getAction()).getRequest().getAttribute("fc_data").toString();
            JSONObject jsonObject = JSONObject.fromObject(fc_data);
            String deviceId = jsonObject.containsKey("deviceId") ? String.valueOf(jsonObject.get("deviceId")) : "";
            String terminalTypeId = jsonObject.containsKey("terminalTypeId") ? String.valueOf(jsonObject.get("terminalTypeId")) : "";
            if(StringUtils.isNotBlank(deviceId) && StringUtils.isNotBlank(terminalTypeId)){
                DeviceKey device = new DeviceKey();
                device.setDeviceId(deviceId);
                device = deviceKeyService.searchEntity(device);
                if(device != null){
                    int deviceTerminalTypeId = device.getTerminalTypeId();
                    int paramTerminalTypeId = Integer.valueOf(terminalTypeId);
                    if(deviceTerminalTypeId != 0 && deviceTerminalTypeId != paramTerminalTypeId){
                        log.debug("刷卡器所属终端类型["+deviceTerminalTypeId+"]与当前终端类型["+paramTerminalTypeId+"]不匹配,停止使用!");
                        action.sendAppErrorMsg("9999");
                        return null;
                    }
                }
            }

            /*Enumeration e = action.getRequest().getHeaderNames();
			String headerName = "";
			while(e.hasMoreElements()){
				headerName = e.nextElement().toString();
				log.error("请求头信息： "+headerName+"="+action.getRequest().getHeader(headerName));
			}*/
            //String[] userIdArray = (String[])params.get("userId");;
            Long userId = null;

            //判断登录是否 还有效
            sessionMap = act.getSession();
            user = (User) sessionMap.get(UserAction.SESSION_USER);
            if (user == null) {

                log.error("用户会话失效，请重新登录！" + action.getRequest().getSession().getId());
                Cookie[] strArray = action.getRequest().getCookies();
                if (strArray != null) {
                    for (Cookie cookie : strArray) {
                        log.error(cookie.getName() + "=" + cookie.getValue());
                    }
                }
                action.sendAppErrorMsg("9990");
                return null;
            } else {//判断是否过期
                //if(SessionOnlineUser.isOld(user)){//过期 就是用户被别人挤下去了
                if (userService.isOldMemcachedUser(user)) {//过期 就是用户被别人挤下去了 使用Memcached
                    sessionMap.remove(UserAction.SESSION_USER);//清除会话中的用户
                    log.error("对不起，您的帐号[" + user.getLoginName() + "]已在别的地方登录，您已经被迫退出。若有疑问请联系管理员，谢谢！");
                    action.sendAppErrorMsg("9991", user.getLoginName());
                    return null;
                }
            }

            js = JSONObject.fromObject(action.getRequest().getAttribute(action.FC_DATA));
            if (js.containsKey("userId"))
                userId = Long.parseLong(js.getString("userId"));
            if (null == userId) {
                log.debug("过滤用户时:userId为null");
            } else {
                //userId = Long.parseLong(userIdArray[0]);
                user = userService.getUserById(userId);
                if (null != user) {
                    log.debug("##user.getDPIStatus() = " + user.getDPIStatus());
                    //log.debug("##user.getBankStatus() = "+user.getBankStatus());

                    //判断实名认证
					/*if(0 == user.getDPIStatus()){//0:认证失败 1:认证通过 2:审核中 3:未申请认证 DEFAULT 3
						action.sendAppErrorMsg("6034");//认证失败
						return null;
					}else if(2 == user.getDPIStatus()){//审核中
						action.sendAppErrorMsg("6033");
						return null;
					}else if(3 == user.getDPIStatus()){//未申请认证
						action.sendAppErrorMsg("6032");
						return null;
					}else if(null == user.getUserName() && !(null==user.getDPIStatus() || 3==user.getDPIStatus().intValue())){
						action.sendAjaxResponse("6032");
						return null;
					}
					//判断银行卡绑定
					if(0 == user.getBankStatus()){//0:认证失败 1:认证通过 2:审核中 3:未申请认证 DEFAULT 3
						action.sendAjaxResponse("-23");
						return null;
					}else if(2 == user.getBankStatus()){
						action.sendAjaxResponse("-24");
						return null;
					}else if(3 == user.getBankStatus()){
						action.sendAjaxResponse("-25");
						return null;
					}*/
                } else {
                    log.error("不存在用户ID为：" + userId + " 的用户");
                }
            }
            log.debug("通过过滤器！");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            action = null;
            act = null;
            sessionMap = null;
            user = null;
            js = null;
        }
        return invocation.invoke();
    }

}
